interface Reminder {
    id?: number;
    date: Date;
    content: string;
  }
  
  class ReminderDB {
    private db: IDBDatabase | null = null;
    private readonly dbName = 'CalendarDB';
    private readonly storeName = 'reminders';
    private readonly version = 1;
  
    async init(): Promise<void> {
      return new Promise((resolve, reject) => {
        const request = indexedDB.open(this.dbName, this.version);
  
        request.onerror = () => {
          reject(request.error);
        };
  
        request.onsuccess = () => {
          this.db = request.result;
          resolve();
        };
  
        request.onupgradeneeded = (event) => {
          const db = (event.target as IDBOpenDBRequest).result;
          if (!db.objectStoreNames.contains(this.storeName)) {
            db.createObjectStore(this.storeName, {
              keyPath: 'id',
              autoIncrement: true,
            });
          }
        };
      });
    }
  
    async addReminder(reminder: Reminder): Promise<number> {
      if (!this.db) await this.init();
      
      return new Promise((resolve, reject) => {
        const transaction = this.db!.transaction([this.storeName], 'readwrite');
        const store = transaction.objectStore(this.storeName);
        const request = store.add(reminder);
  
        request.onsuccess = () => {
          resolve(request.result as number);
        };
  
        request.onerror = () => {
          reject(request.error);
        };
      });
    }
  
    async getAllReminders(): Promise<Reminder[]> {
      if (!this.db) await this.init();
  
      return new Promise((resolve, reject) => {
        const transaction = this.db!.transaction([this.storeName], 'readonly');
        const store = transaction.objectStore(this.storeName);
        const request = store.getAll();
  
        request.onsuccess = () => {
          // 将存储的日期字符串转换回 Date 对象
          const reminders = request.result.map(reminder => ({
            ...reminder,
            date: new Date(reminder.date)
          }));
          resolve(reminders);
        };
  
        request.onerror = () => {
          reject(request.error);
        };
      });
    }
  
    async deleteReminder(id: number): Promise<void> {
      if (!this.db) await this.init();
  
      return new Promise((resolve, reject) => {
        const transaction = this.db!.transaction([this.storeName], 'readwrite');
        const store = transaction.objectStore(this.storeName);
        const request = store.delete(id);
  
        request.onsuccess = () => {
          resolve();
        };
  
        request.onerror = () => {
          reject(request.error);
        };
      });
    }
}
  
  export const reminderDB = new ReminderDB();
  export type { Reminder };